import Vue from 'vue'
import Vuex from 'vuex'
import { FetchLogin, FetchGetUserInfo } from '@/api'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: '',
    userInfo: {},
    // 交通灯控制信号
    traffic: 0
  },
  mutations: {
    SET_TRAFFIC(state, data) {
      // console.log('data:...:', data)
      state.traffic = data;
    },
    setInfo(state, info) {
      // state.obj.gender = info
      Vue.set(state.obj, 'gender', info)
      console.log('vuex:....', state.obj)
    },
    SET_LOGIN(state, data) {
      state.token = data;
      localStorage.setItem('token', data)
    },
    SET_USERINFO(state, data) {
      state.userInfo = data;
    }
  },
  actions: { // 命名规则： GetLogin  首字母大写，其他驼峰
    GetLogin({ commit }, { username, password }) { // commit 提交给mutaions
      return new Promise((resolve, reject) => {
        FetchLogin({username, password}).then(response => {
          console.log('response:....:', response)
          if (response.code === 1) {
            commit('SET_LOGIN', response.data.token)
            resolve({code: 1, msg: 'success'})
          } else {
            reject({code: -1, msg: 'fail'})
          }
        })
      })
    },
    GetUserInfo({ commit }, data) {
      return new Promise((resolve, reject) => {
        FetchGetUserInfo({token: 123}).then(response => {
          if (response.code === 1) {
            commit('SET_USERINFO', response.data.userInfo)
            resolve({code: 1, msg: 'success'})
          } else {
            reject({code: -1, msg: 'fail'})
          }
        })
      })
    }
  },
  modules: {
  }
})
